package com.lianniu.web.tea.order.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.lianniu.web.base.BaseResult;
import com.lianniu.web.constants.ErrorCode;
import com.lianniu.web.tea.order.dao.TeaOrderDao;
import com.lianniu.web.tea.order.model.TeaOrder;
import com.lianniu.web.tea.order.service.ITeaOrderService;
import com.lianniu.web.tea.product.dao.TeaProductDao;
import com.lianniu.web.tea.product.model.TeaProduct;
import com.lianniu.web.tea.product.service.impl.TeaProductServiceImpl;
import com.lianniu.web.tea.user.addr.dao.TeaUserAddrDao;
import com.lianniu.web.tea.user.addr.model.TeaUserAddr;
import com.lianniu.web.tea.user.favour.model.TeaFavour;
import com.lianniu.web.tea.user.info.dao.TeaFrontusersDao;
import com.lianniu.web.tea.user.info.model.TeaFrontusers;
import com.lianniu.web.tea.user.info.service.ITeaInfoService;
import com.lianniu.web.util.DateUtil;
import com.lianniu.web.util.HttpUtils;
import com.lianniu.web.util.TeaContant;
import com.lianniu.web.util.UUIDUtil;

@Service
@Transactional
public class TeaOrderServiceImpl implements ITeaOrderService {

	private final static Logger logger = Logger.getLogger(TeaProductServiceImpl.class);
	
	@Autowired
	private TeaProductDao teaProductDao;
	
	@Autowired
	private TeaUserAddrDao teaUserAddrDao;
	
	@Autowired
	private TeaOrderDao teaOrderDao;
	
	@Autowired
	private ITeaInfoService teaInfoService;
	
	/**
	 * 用户点击购买后返回前台生成订单所需的信息
	 */
	@SuppressWarnings("unchecked")
	public BaseResult getOrderInfoBefore(String userId, String productId) {
		logger.info("TeaOrderServiceImpl getOrderInfoBefore start");
		TeaProduct teaProduct = teaProductDao.selectProOeder(Long.valueOf(productId));
		TeaUserAddr teaUserAddr =  teaUserAddrDao.selectDefaultAddr(userId);
		Map result = new HashMap();
		result.put("teaProduct", teaProduct);
		result.put("teaUserAddr", teaUserAddr);
		logger.info("TeaOrderServiceImpl getOrderInfoBefore end");
		return BaseResult.success(result);
	}

	@Override
	public BaseResult saveOrder(TeaOrder order) {
		TeaProduct teaProduct = teaProductDao.selectByPrimaryKey(Long.valueOf(order.getProductid()));
		if(!(teaProduct.getPriceretailguide().compareTo(order.getPerunit())==0)){
			return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo);
		}
		//校验一下这个订单是否正确
		order.setId(UUIDUtil.getUUID());
		BigDecimal freight = order.getFreight();
		int conut = order.getConut();
		BigDecimal perunit = order.getPerunit();
		BigDecimal sum =freight.add(perunit.multiply(new BigDecimal(Integer.toString(conut))));
		if(!(sum.compareTo(order.getTotalunit())==0)){
			//不相等
			return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo);
		}
		order.setId(UUIDUtil.getUUID());
		order.setOrderno(DateUtil.getNowTime().substring(0, 10).replaceAll("-", "")+Long.toString(System.currentTimeMillis()));
		order.setStatus(TeaContant.TEA_ORDER_STATUS_START);
		order.setAddtime(DateUtil.getNowTime());
		teaOrderDao.insert(order);
		return BaseResult.success(order);
	}

	@Override
	public BaseResult getOrderInfo(String orderId) {
		TeaOrder teaOrder = teaOrderDao.selectByPrimaryKey(orderId);
		TeaProduct teaProduct =teaProductDao.selectProOeder(Long.valueOf(teaOrder.getProductid()));
		TeaUserAddr teaUserAddr = teaUserAddrDao.selectByPrimaryKey(teaOrder.getAddrid());
		if(Integer.valueOf(teaOrder.getStatus())>2){
			String wayno = teaOrder.getWayno();
			try {
				String host = "http://jisukdcx.market.alicloudapi.com";
			    String path = "/express/query";
			    String method = "GET";
			    String appcode = "81212a84de3a46cdaa554958bf2b4027";
			    Map<String, String> headers = new HashMap<String, String>();
			    //鏈�鍚庡湪header涓殑鏍煎紡(涓棿鏄嫳鏂囩┖鏍�)涓篈uthorization:APPCODE 83359fd73fe94948385f570e3c139105
			    headers.put("Authorization", "APPCODE " + appcode);
			    Map<String, String> querys = new HashMap<String, String>();
			    querys.put("number", wayno);
			    querys.put("type", "auto");
			    HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
		    	String string = EntityUtils.toString(response.getEntity());
		    	teaOrder.setWayInfo(string);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		teaOrder.setTeaProduct(teaProduct);
		teaOrder.setTeaUserAddr(teaUserAddr);
		return BaseResult.success(teaOrder);
	}

	@Override
	public BaseResult cancleOrder(String orderId, String status) {
		logger.info("TeaOrderServiceImpl cancleOrder start");
		TeaOrder teaOrder = new TeaOrder();
		teaOrder.setId(orderId);
		if(TeaContant.TEA_ORDER_STATUS_RECIVE.equals(status)){
			teaOrder.setStatus(TeaContant.TEA_ORDER_STATUS_DELETE);
		}else if(TeaContant.TEA_ORDER_STATUS_SEND.equals(status)){
			teaOrder.setStatus(TeaContant.TEA_ORDER_STATUS_RECIVE);
		}else{
			teaOrder.setStatus(TeaContant.TEA_ORDER_STATUS_CANCLE);
		}
		teaOrderDao.updateByPrimaryKeySelective(teaOrder);
		logger.info("TeaOrderServiceImpl cancleOrder end");
		return BaseResult.success();
	}

	@Override
	public BaseResult getOrderListByUserId(Map param) {
		List<TeaOrder> teaOrderRes = new ArrayList<TeaOrder>();
		List<TeaOrder> teaOrderList = teaOrderDao.getOrderListByUserId(param);
		if(!CollectionUtils.isEmpty(teaOrderList)){
//			for (TeaOrder teaOrder : teaOrderList) {
//				TeaProduct teaProduct =teaProductDao.selectProOeder(Long.valueOf(teaOrder.getProductid()));
//				TeaUserAddr teaUserAddr = teaUserAddrDao.selectByPrimaryKey(teaOrder.getAddrid());
//				TeaFrontusers teaInfo = teaInfoService.getTeaInfoByUserId(teaProduct.getAdduser());
//				teaOrder.setTeaFrontusers(teaInfo);
//				teaOrder.setTeaProduct(teaProduct);
//				teaOrder.setTeaUserAddr(teaUserAddr);
//			}
			for (TeaOrder teaOrder : teaOrderList) {
				BaseResult baseResult = getOrderInfo(teaOrder.getId());
				TeaOrder teaOrderRe = (TeaOrder) baseResult.getData();
				teaOrderRes.add(teaOrderRe);
			}
		}
		return BaseResult.success(teaOrderRes);
	}

	@Override
	public BaseResult makeSure(String orderId) {
		TeaOrder teaOrder = new TeaOrder();
		teaOrder.setId(orderId);
		teaOrder.setStatus(TeaContant.TEA_ORDER_STATUS_RECIVE);
		teaOrderDao.updateByPrimaryKeySelective(teaOrder);
		System.err.println("success");
		return BaseResult.success();
	}

	@Override
	public BaseResult updateTeaOrder(TeaOrder order) {
		// TODO Auto-generated method stub
		teaOrderDao.updateByPrimaryKeySelective(order);
		return BaseResult.success();
	}

}
